package com.sea.base.widget

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.ViewConfiguration
import android.widget.FrameLayout
import com.sea.base.ext.view.getChildOrNull
import kotlin.math.absoluteValue
import kotlin.math.sign

/**
 * 主要解决嵌套的横竖滑被父类优先拦截的问题
 * 比如：NestedScrollView套ViewPager2快速斜滑事件被却NestedScrollView拦截了
 * 注意：第一个Child必须是可滑动的view，比如：RecyclerView、ViewPager2、NestedScrollView
 */
class NestedScrollableOptFrameLayout @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
    FrameLayout(context, attrs, defStyleAttr) {
    private val touchSlop = ViewConfiguration.get(context).scaledTouchSlop

    private var initialX = 0f
    private var initialY = 0f

    private val child0 get() = getChildOrNull(0)

    private fun canChildHorizontalScroll(delta: Float): Boolean {
        val direction = -delta.sign.toInt()
        return child0?.canScrollHorizontally(direction) ?: false
    }

    private fun canChildVerticalScroll(delta: Float): Boolean {
        val direction = -delta.sign.toInt()
        return child0?.canScrollVertically(direction) ?: false
    }

    override fun onInterceptTouchEvent(e: MotionEvent): Boolean {
        handleInterceptTouchEvent(e)
        return super.onInterceptTouchEvent(e)
    }

    private fun handleInterceptTouchEvent(e: MotionEvent) {
        when (e.action) {
            MotionEvent.ACTION_DOWN -> {
                initialX = e.x
                initialY = e.y
                requestParentTouch(true)
            }

            MotionEvent.ACTION_MOVE -> {
                val dx = e.x - initialX
                val dy = e.y - initialY
                val absDy = dy.absoluteValue
                val absDx = dx.absoluteValue
                //太小的话没意义直接跳过
                if (absDx < touchSlop / 3 && absDy < touchSlop / 3) return

                if (absDx > absDy) {
                    //横向滑动
                    requestParentTouch(canChildHorizontalScroll(dx))
                } else {
                    //竖向滑动
                    requestParentTouch(canChildVerticalScroll(dx))
                }
            }
        }
    }

    private fun requestParentTouch(isDisallow: Boolean) {
        parent.requestDisallowInterceptTouchEvent(isDisallow)
    }
}